package com.mrobuy.jd.api.apply;

import com.google.gson.Gson;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.supplier.ProductManagementService.response.find.ApplyProductDto;
import com.jd.open.api.sdk.request.supplier.VcItemProductAppliesFindRequest;
import com.jd.open.api.sdk.response.supplier.VcItemProductAppliesFindResponse;
import com.mrobuy.jd.api.JosClient;
import com.mrobuy.jdvc.entity.VCProductApply;

import java.util.ArrayList;
import java.util.List;

public class ProductApplyFindClient extends JosClient<List<VCProductApply>> {

    private static final int PAGE_SIZE = 50;

    private VcItemProductAppliesFindRequest request = new VcItemProductAppliesFindRequest();

    public ProductApplyFindClient(JdClient client) {
        super(client);
    }

    @Override
    public List<VCProductApply> call() throws Exception {

        List<VCProductApply> applies = new ArrayList<>();

        request.setLength(PAGE_SIZE);
        int page = 1;

        Gson gson = new Gson();

        while ( true ) {
            request.setPage(page++);

            LOG.info("[REQ]" + request.getApiMethod() + ": " + request.getAppJsonParams());

            VcItemProductAppliesFindResponse response= client.execute(request);
            if ( response.getJosResultDto()==null || response.getJosResultDto().getResult()==null
                    || response.getJosResultDto().getResult().size()<PAGE_SIZE || response.getJosResultDto().getResult().size()==0  ) {
                break;
            }

            LOG.info("总记录数目: " + response.getJosResultDto().getCount());
            for (ApplyProductDto applyProductDto : response.getJosResultDto().getResult()) {
                VCProductApply productApply = gson.fromJson(gson.toJsonTree(applyProductDto), VCProductApply.class);
                if ( productApply!=null ) {
                    applies.add(productApply);
                }
            }


        }

        return applies;
    }

    public ProductApplyFindClient setWareId(String ware_id) {
        request.setWareId(ware_id);
        return this;
    }

    public ProductApplyFindClient setWareName(String wareName) {
        request.setWareName(wareName);
        return this;
    }

    public ProductApplyFindClient setState(Integer state) {
       request.setState(state);
        return this;
    }

    public ProductApplyFindClient setBeginTime(String beginTime) {
        request.setBeginTime(beginTime);
        return this;
    }

    public ProductApplyFindClient setEndTime(String endTime) {
        request.setEndTime(endTime);
        return this;
    }
}
